package com.yoyo.yyadsdk.util;

import android.content.Context;

import com.yoyo.yyadsdk.bean.dao.LocalPullEntity;
import com.yoyo.yyadsdk.bean.dao.PullEntity;
import com.yoyo.yyadsdk.bean.dao.RuleListEntity;
import com.yoyo.yyadsdk.config.PullFeature;

import java.util.ArrayList;
import java.util.List;

public class PullUtils {

    public static List<PullEntity> getPullEntities(@PullFeature.PullTypeFlags int actionType) {
        List<PullEntity> res = new ArrayList<>();
        PullType pullType = new PullType(actionType).invoke();
        List<PullEntity> pullEntities = pullType.getPullEntities();
        List<LocalPullEntity> localPullEntityList = pullType.getLocalPullEntityList();
        List<RuleListEntity> ruleListEntityList = pullType.getRuleListEntityList();
        long lastTime = pullType.getLastTime();
        for (PullEntity p : pullEntities) {
            //校验是否符合拉活条件
            if (checkPull(p, localPullEntityList, ruleListEntityList, lastTime))
                continue;
            res.add(p);
        }
        return res;
    }

    /**
     * 根据限制条件获取目标包名
     *
     * @param actionType 拉活类型
     * @return 要启动的包名 可能为空
     */
    public static PullEntity getPullEntity(@PullFeature.PullTypeFlags int actionType) {
        PullType pullType = new PullType(actionType).invoke();
        List<PullEntity> pullEntities = pullType.getPullEntities();
        List<LocalPullEntity> localPullEntityList = pullType.getLocalPullEntityList();
        List<RuleListEntity> ruleListEntityList = pullType.getRuleListEntityList();
        long lastTime = pullType.getLastTime();
        for (PullEntity p : pullEntities) {
            //校验是否符合拉活条件
            if (checkPull(p, localPullEntityList, ruleListEntityList, lastTime))
                continue;
            return p;
        }
        return null;
    }

    /**
     * 校验是否符合拉活条件
     *
     * @return True is Not in config
     */
    private static boolean checkPull(PullEntity p, List<LocalPullEntity> localPullEntityList, List<RuleListEntity> ruleListEntityList, long lastTime) {
        //判断应用是否符合上次活跃时间间隔
        long timeMillis = System.currentTimeMillis();
        if (p.getInActivity() > 0 && timeMillis - lastTime < p.getInActivity() * TimeUtils.SECOND)
            return true;

        //判断是否在有效期内 (数据库判断了)
//        if (timeMillis > p.getEndTime() || timeMillis < p.getStartTime())
//            return true;

        //判断是否在拉活周期内
        Integer duringEndTime = Integer.getInteger(p.getDuringEndTime());
        Integer duringStartTime = Integer.getInteger(p.getDuringStartTime());
        Integer timeInHHmm = TimeUtils.getHHmm();
        if (timeInHHmm != null && duringEndTime != null && duringStartTime != null) {
            //根据起始区间判断当前是否在允许时间段内
            if (duringEndTime > duringStartTime ?
                    (timeInHHmm > duringEndTime || timeInHHmm < duringStartTime) :
                    (timeInHHmm > duringEndTime && timeInHHmm < duringStartTime))
                return true;
        }

        //判断本地是否有保存的拉活记录
        LocalPullEntity l = null;
        for (LocalPullEntity localPullEntity : localPullEntityList)
            if (p.getId() == localPullEntity.getPullId()) {
                l = localPullEntity;
                break;
            }

        if (l != null) {
            //是否超过拉活总次数
            if (p.getFrequency() < l.getPullTimes())
                return true;

            //判断周期内的拉活次数
            if (TimeUtils.isToday(l.getPullTime()) && l.getPullCount() >= p.getPullTimes())
                return true;
        }

        //判断是否有黑白名单限制
        RuleListEntity r = null;
        for (RuleListEntity ruleListEntity : ruleListEntityList)
            if (p.getRuleId() == ruleListEntity.getRuleId()) {
                r = ruleListEntity;
                break;
            }

        if (r != null) {
            if (r.getType() == PullFeature.PULL_WHITE_LIST) {
                //白名单
                return r.getInWhiteRule();
            } else {
                //黑名单
                return !r.getInBlackRule();
            }
        }
        return false;
    }

    public static boolean inBlackRuleList(Context context, RuleListEntity r) {
        String city = SpUtil.getCity(context);
        if (strInList(r.getCity(), city))
            return true;
        String pkgName = context.getPackageName();
        if (strInList(r.getPkg(), pkgName))
            return true;
        String model = SystemUtil.getSystemModel();
        if (strInList(r.getModel(), model))
            return true;
        String deviceBrand = SystemUtil.getDeviceBrand();
        if (strInList(r.getChannel(), deviceBrand))
            return true;
        String imei = SystemUtil.getIMEI(context);
        if (strInList(r.getImei(), imei))
            return true;
        String country = SpUtil.getCountry(context);
        if (strInList(r.getCountry(), country))
            return true;
        return PackageUtil.isInUserActiveRules(context, r.getUserActive(), false);
    }

    public static boolean inWhiteRuleList(Context context, RuleListEntity r) {
        String city = SpUtil.getCity(context);
        if (strNotInList(r.getCity(), city))
            return false;
        String pkgName = context.getPackageName();
        if (strNotInList(r.getPkg(), pkgName))
            return false;
        String model = SystemUtil.getSystemModel();
        if (strNotInList(r.getModel(), model))
            return false;
        String deviceBrand = SystemUtil.getDeviceBrand();
        if (strNotInList(r.getChannel(), deviceBrand))
            return false;
        String imei = SystemUtil.getIMEI(context);
        if (strNotInList(r.getImei(), imei))
            return false;
        String country = SpUtil.getCountry(context);
        if (strNotInList(r.getCountry(), country))
            return false;
        return !PackageUtil.isInUserActiveRules(context, r.getUserActive(), true);
    }

    private static boolean strNotInList(List<String> list, String str) {
        return str != null && list != null && list.size() > 0 && !list.contains(str);
    }

    private static boolean strInList(List<String> list, String str) {
        return str != null && list != null && list.size() > 0 && list.contains(str);
    }
}
